package com.software.cool.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 日期处理
 *
 * @Author: wulihua
 * @Date: 2019/4/18 17:01
 */
public class DateUtils {

    public static final String Y = "yyyy";
    public static final String YMD = "yyyyMMdd";
    public static final String YMD_SLASH = "yyyy/MM/dd";
    public static final String YMD_DASH = "yyyy-MM-dd";
    public static final String YMD_DASH_MM = "yyyy-MM";
    public static final String YMD_MM = "yyyyMM";
    public static final String YMD_DASH_MM_STR = "yyyyMM";
    public static final String YMD_DASH_WITH_TIME = "yyyy-MM-dd HH:mm:ss";
    public static final String YMD_WITH_TIME = "yyyy/MM/dd HH:mm:ss";
    /**
     * 年月日时分秒
     */
    public static final String YMD_DASH_WITH_TIME_STR = "yyyyMMddHHmmss";
    /**
     * 年月日时分秒毫秒
     */
    public static final String YMD_DASH_WITH_MITIME_STR = "yyyyMMddHHmmssSSS";
    public static final String YMD_DASH_WITH_MITIME = "yyyy-MM-dd HH:mm:ss:SSS";
    public static final String YDM_SLASH = "yyyy/dd/MM";
    public static final String YDM_DASH = "yyyy-dd-MM";
    public static final String HM = "HHmm";
    public static final String HM_COLON = "HH:mm";
    public static final String HMS = "hh:mm:ss";
    public static final long MONTH = 30 * 24 * 60 * 60 * 1000L;
    public static final long DAY = 24 * 60 * 60 * 1000L;
    public static final long SECOND = 24 * 60 * 60 * 24 * 60 * 1000L;
    /**
     * 一天的毫秒数
     */
    public static final long ND = 1000 * 24 * 60 * 60;
    /**
     * 一小时的毫秒数
     */
    public static final long NH = 1000 * 60 * 60;
    /**
     * 一分钟的毫秒数
     */
    public static final long NM = 1000 * 60;
    /**
     * 一秒钟的毫秒数
     */
    public static final long NS = 1000;

    private static int weeks = 0;

    private static final Map<String, DateFormat> DFS = new HashMap<String, DateFormat>();

    private static final Log log = LogFactory.getLog(DateUtils.class);

    public static int TIME_SPLIT_LENGTH = 3;

    private DateUtils() {

    }

    /**
     * Java将Unix时间戳转换成指定格式日期字符串
     *
     * @param timestampString 时间戳 如："1473048265";
     * @param formats         要格式化的格式 默认："yyyy-MM-dd HH:mm:ss";
     * @return 返回结果 如："2016-09-05 16:06:42";
     */
    public static String timeStamp2Date(String timestampString, String formats) {
        if (StringUtils.isBlank(formats)) {
            formats = "yyyy-MM-dd HH:mm:ss";
        }
        Long timestamp = Long.parseLong(timestampString, 16) * 1000;
        String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
        return date;
    }

    /**
     * 毫秒转小时
     *
     * @return
     */
    public static double formatHour(long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        // Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        // Long milliSecond = ms - day * dd - hour * hh - minute * mi - second *
        // ss;
        BigDecimal b1 = new BigDecimal(Double.toString(minute));
        BigDecimal b2 = new BigDecimal(Double.toString(60));
        int scale = 2;
        return hour + b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 分钟转小时
     *
     * @param minute
     * @return
     */
    public static double minFormatHour(int minute) {
        BigDecimal b1 = new BigDecimal(Double.toString(minute));
        BigDecimal b2 = new BigDecimal(Double.toString(60));
        int scale = 2;
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 毫秒转分钟
     *
     * @return
     */
    public static double formatMinute(long ms) {
        int scale = 2;
        BigDecimal b1 = new BigDecimal(Double.toString(ms));
        BigDecimal b2 = new BigDecimal(Double.toString(1000));
        double ss = b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
        BigDecimal b3 = new BigDecimal(Double.toString(ss));
        BigDecimal b4 = new BigDecimal(Double.toString(60));
        return b3.divide(b4, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 毫秒转秒
     *
     * @return
     */
    public static double formatSecond(long ms) {
        int scale = 2;
        BigDecimal b1 = new BigDecimal(Double.toString(ms));
        BigDecimal b2 = new BigDecimal(Double.toString(1000));
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    /**
     * 返回当天日期
     */
    public static String nowDate() {
        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH);
        String dateStr = sd.format(date);
        return dateStr;
    }

    /**
     * 返回本周开始日期 author wxp
     */
    public static String firstWeekDay() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH);
        cal.add(Calendar.DAY_OF_WEEK, -1);
        String firstweekDay = sd.format(cal.getTime());
        return firstweekDay;
    }

    /**
     * 返回本周结束日期
     *
     * @return
     */
    public static String endWeekDay() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH);
        cal.add(Calendar.DAY_OF_WEEK, 5);
        String firstweekDay = sd.format(cal.getTime());
        return firstweekDay;
    }

    public static String firstdayStr() {
        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH);
        String firstDay = sd.format(DateUtils.firstDay(date));
        return firstDay;
    }

    /**
     * 返回本月结束日期 author wxp
     */
    public static String lastdayStr() {
        Date date = new Date();
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH);
        String lastDay = sd.format(DateUtils.lastDay(date));
        return lastDay;
    }

    /**
     * 秒转秒.毫秒  eg:9"235
     * @param secondTime 9.235
     * @return
     */
    public static String secondConvertMillisecondStr(String secondTime) {
        String result="0\"000";
        String[] array=secondTime.split("\\.");
        if(array.length>0){
            int second=CommonUtils.parseIntegerData(array[0]);
            int minllisecond=CommonUtils.parseIntegerData(array[1]);
            result=second+"\""+minllisecond;
        }else{
            result=secondTime+"\"";
        }
        return result;
    }

    /**
     * 秒转分秒  eg:3'30"
     * @param secondTime
     * @return
     */
    public static String secondConvertMinsecStr(BigDecimal secondTime) {
        String result="";
        int millisecond=secondTime.multiply(new BigDecimal(1000)).intValue();
        String res="00:00";
        if (millisecond <= 0) {
            res="00:00";
        }
        // 初始化Formatter的转换格式
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        res= formatter.format(millisecond);
        String[] array=res.split(":");
        int min=CommonUtils.parseIntegerData(array[0]);
        int second=CommonUtils.parseIntegerData(array[1]);
        result=min+"'"+second+"\"";
        return result;
    }

    /**
     * 秒转分秒 eg:3.30
     * @param secondTime
     * @return
     */
    public static BigDecimal secondConvertMinsecBd(BigDecimal secondTime) {
        BigDecimal result=BigDecimal.ZERO;
        int millisecond=secondTime.multiply(new BigDecimal(1000)).intValue();
        String res="00:00";
        if (millisecond <= 0) {
            res="00:00";
        }
        // 初始化Formatter的转换格式
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        res= formatter.format(millisecond);
        res=res.replace(":",".");
        result=new BigDecimal(res);
        return result;
    }

    /**
     * 毫秒转格式：00:00:000
     *
     * @param time
     * @return
     */
    public static String getTimeFromInt(int time) {
        if (time <= 0) {
            return "00:00:000";
        }
        // 初始化Formatter的转换格式
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss:SSS");
        String hms = formatter.format(time);
        return hms;
    }

    /**
     * 00:00:00转毫秒格式
     *
     * @param str
     * @return
     */
    public static int getTimeFromStr(String str) {
        int result = 0;
        if (CommonUtils.isNotBlank(str)) {
            String[] timeArray = str.split(":");
            if (timeArray.length == TIME_SPLIT_LENGTH) {
                int hh = CommonUtils.parseIntegerData(timeArray[0]) * 60 * 60 * 1000;
                int mm = CommonUtils.parseIntegerData(timeArray[1]) * 60 * 1000;
                int ss = CommonUtils.parseIntegerData(timeArray[2]) * 1000;
                result = hh + mm + ss;
            }
        }
        return result;
    }

    /**
     * 返回格式 HH:mm:ss time 秒数
     */
    public static String formatMHS(int time) {
        SimpleDateFormat sd = new SimpleDateFormat("HH:mm:ss");
        sd.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        String str = sd.format(time);
        return str;
    }

    /**
     * 如：01:22:12
     *
     * @param time
     * @return
     */
    public static long getSec(String time) {
        if (CommonUtils.isBlank(time)) {
            time = "00:00:00";
        }
        String[] my = time.split(":");
        int hour = Integer.parseInt(my[0]);
        int min = Integer.parseInt(my[1]);
        int sec = Integer.parseInt(my[2]);
        long totalSec = hour * 3600 + min * 60 + sec;
        return totalSec;
    }

    /**
     * 格式化日期
     *
     * @param pattern 传入日期格式如：yyyy-MM-dd HH:mm:ss
     * @return DateFormat
     */
    public static DateFormat getFormat(String pattern) {
        DateFormat format = DFS.get(pattern);
        if (format == null) {
            format = new SimpleDateFormat(pattern);
            DFS.put(pattern, format);
        }
        return format;
    }

    /**
     * @param source
     * @param pattern
     * @return Date
     */
    public static Date parse(String source, String pattern) {
        if (source == null) {
            return null;
        }
        Date date;
        try {
            date = getFormat(pattern).parse(source);
        } catch (ParseException e) {
            if (log.isDebugEnabled()) {
                log.debug(source + " doesn't match " + pattern);
            }
            return null;
        }
        return date;
    }

    public static Timestamp getCurrentTimestamp() {
        Date now = new Date();
        Timestamp tt = new Timestamp(now.getTime());
        return tt;
    }

    public static Timestamp getCurrentTimestampYMD() {
        Date now = DateUtils.parse(DateUtils.format(new Date(), DateUtils.YMD_DASH), DateUtils.YMD_DASH);
        Timestamp tt = new Timestamp(now.getTime());
        return tt;
    }

    /**
     * 格式化字符串日期
     *
     * @param date
     * @param pattern
     * @return 格式化字符串日期
     */
    public static String format(Date date, String pattern) {
        if (date == null) {
            return null;
        }
        return getFormat(pattern).format(date);
    }

    /**
     * 格式化Timestamp
     *
     * @param tt
     * @param pattern
     * @return
     */
    public static String format(Timestamp tt, String pattern) {
        if (tt == null) {
            return null;
        }
        Date date = new Date(tt.getTime());
        return getFormat(pattern).format(date);
    }

    /**
     * @param year  年
     * @param month 月(1-12)
     * @param day   日(1-31)
     * @return 输入的年、月、日是否是有效日期
     */
    public static boolean isValid(int year, int month, int day) {
        int monthLength = 13;
        int dayLength = 32;
        if (month > 0 && month < monthLength && day > 0 && day < dayLength) {
            // month of calendar is 0-based
            int mon = month - 1;
            Calendar calendar = new GregorianCalendar(year, mon, day);
            if (calendar.get(Calendar.YEAR) == year && calendar.get(Calendar.MONTH) == mon
                    && calendar.get(Calendar.DAY_OF_MONTH) == day) {
                return true;
            }
        }
        return false;
    }

    /**
     * Date日期转换成Calendar日历
     *
     * @param date
     * @return
     */
    private static Calendar convert(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar;
    }

    /**
     * 返回指定年数位移后的日期
     */
    public static Date yearOffset(Date date, int offset) {
        return offsetDate(date, Calendar.YEAR, offset);
    }

    /**
     * 返回指定月数位移后的日期
     */
    public static Date monthOffset(Date date, int offset) {
        return offsetDate(date, Calendar.MONTH, offset);
    }

    /**
     * 返回指定天数位移后的日期
     */
    public static Date dayOffset(Date date, int offset) {
        return offsetDate(date, Calendar.DATE, offset);
    }

    /**
     * 返回指定小时数位移后的日期
     */
    public static Date hourOffset(Date date, int offset) {
        return offsetDate(date, Calendar.HOUR, offset);
    }
    /**
     * 返回指定分钟数位移后的日期
     */
    public static Date minOffset(Date date, int offset) {
        return offsetDate(date, Calendar.MINUTE, offset);
    }

    /**
     * 返回指定秒数位移后的日期
     */
    public static Date secondOffset(Date date, int offset) {
        return offsetDate(date, Calendar.SECOND, offset);
    }

    /**
     * 返回指定日期相应位移后的日期
     *
     * @param date   参考日期
     * @param field  位移单位，见 {@link Calendar}
     * @param offset 位移数量，正数表示之后的时间，负数表示之前的时间
     * @return 位移后的日期
     */
    public static Date offsetDate(Date date, int field, int offset) {
        Calendar calendar = convert(date);
        calendar.add(field, offset);
        return calendar.getTime();
    }

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    public static String getWeek4Date(Date dt) {
        String[] weekDays = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    /**
     * 返回当月第一天的日期
     */
    public static Date firstDay(Date date) {
        Calendar calendar = convert(date);
        calendar.set(Calendar.DATE, 1);
        return calendar.getTime();
    }

    /**
     * 返回当月最后一天的日期
     */
    public static Date lastDay(Date date) {
        Calendar calendar = convert(date);
        calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
        return calendar.getTime();
    }

    /**
     * 返回两个日期间的差异天数
     *
     * @param date1 参照日期
     * @param date2 比较日期
     * @return 参照日期与比较日期之间的天数差异，正数表示参照日期在比较日期之后，0表示两个日期同天，负数表示参照日期在比较日期之前
     */
    public static int dayDiff(Date date1, Date date2) {
        long diff = date1.getTime() - date2.getTime();
        return (int) (diff / DAY);
    }

    /**
     * 返回两个日期间的差异月份
     *
     * @param date1 参照日期
     * @param date2 比较日期
     * @return 参照日期与比较日期之间的天数差异，正数表示参照日期在比较日期之后，0表示两个日期同天，负数表示参照日期在比较日期之前
     */
    public static int monthDiff(Date date1, Date date2) {
        long diff = date1.getTime() - date2.getTime();
        return (int) (diff / MONTH);
    }

    /**
     * 返回两个日期间的差异秒数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int mmDiff(Date date1, Date date2) {
        long diff = date1.getTime() - date2.getTime();
        // 计算差多少天
        long day = diff / ND;
        // 计算差多少分钟
        long min = diff % ND % NH / NM + day * 24 * 60;
        // 计算差多少秒
        long sec = diff % ND % ND % NM / NS;
        return (int) sec;
    }

    /**
     * 返回两个日期间的差异秒数
     *
     * @return
     */
    public static int mmDiff(String startTime, String endTime) {
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH_WITH_TIME);
        long diff = 0;
        long min = 0;
        long sec = 0;
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            // 计算差多少天
            long day = diff / ND;
            // 计算差多少分钟
            min = diff % ND % NH / NM + day * 24 * 60;
            // 计算差多少秒
            sec = (min * 60) + diff % ND % ND % NM / NS;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return (int) sec;
    }

    /**
     * 返回两个日期间的差异分钟数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int secondDiff(Date date1, Date date2) {
        long from;
        int minutes = 0;
        try {
            from = date1.getTime();
            long to = date2.getTime();
            minutes = (int) ((to - from) / (1000 * 60));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (int) minutes;
    }

    /**
     * 返回两个日期间的差异分钟数
     *
     * @return
     */
    public static int secondDiff(String startTime, String endTime) {
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH_WITH_TIME);
        long from;
        int minutes = 0;

        try {
            if (CommonUtils.isNotBlank(startTime) && CommonUtils.isNotBlank(endTime)) {
                from = sd.parse(startTime).getTime();
                long to = sd.parse(endTime).getTime();
                minutes = (int) ((to - from) / (1000 * 60));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return minutes;
    }

    /**
     * 返回两个日期间的差异小时数
     *
     * @return
     */
    public static double hoursDiff(Date startTime, Date endTime) {
        try {
            if (startTime!=null && endTime!=null) {
                long from = startTime.getTime();
                long to = endTime.getTime();
                long number = to - from;
                if (number != 0) {
                    BigDecimal num = new BigDecimal(number);
                    BigDecimal hours = num.divide(new BigDecimal(60 * 60 * 1000), 2, BigDecimal.ROUND_HALF_UP);
                    return hours.doubleValue();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 返回两个日期间的差异小时数
     *
     * @return
     */
    public static double hoursDiff(String startTime, String endTime) {
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH_WITH_TIME);
        try {
            if (CommonUtils.isNotBlank(startTime) && CommonUtils.isNotBlank(endTime)) {
                long from = sd.parse(startTime).getTime();
                long to = sd.parse(endTime).getTime();
                long number = to - from;
                if (number!= 0) {
                    BigDecimal num = new BigDecimal(number);
                    BigDecimal hours = num.divide(new BigDecimal(60 * 60 * 1000), 2, BigDecimal.ROUND_HALF_UP);
                    return hours.doubleValue();
                }
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static Long dateDiff(String startTime, String endTime, String format, String str) {
        // 按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(format);
        // 一天的毫秒数
        long nd = 1000 * 24 * 60 * 60;
        // 一小时的毫秒数
        long nh = 1000 * 60 * 60;
        // 一分钟的毫秒数
        long nm = 1000 * 60;
        // 一秒钟的毫秒数
        long ns = 1000;
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        long sec = 0;
        // 获得两个时间的毫秒时间差异
        String hourStr = "h";
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            // 计算差多少天
            day = diff / nd;
            // 计算差多少小时
            hour = diff % nd / nh + day * 24;
            // 计算差多少分钟
            min = diff % nd % nh / nm + day * 24 * 60;
            // 计算差多少秒
            sec = diff % nd % nh % nm / ns;


            if (hourStr.equalsIgnoreCase(str)) {
                return hour;
            } else {
                return min;
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (hourStr.equalsIgnoreCase(str)) {
            return hour;
        } else {
            return min;
        }
    }

    public static String dateDiff(String startTime, String endTime) {
        String result = "";
        // 按照传入的格式生成一个simpledateformate对象
        SimpleDateFormat sd = new SimpleDateFormat(YMD_DASH_WITH_TIME);
        // 一天的毫秒数
        long nd = 1000 * 24 * 60 * 60;
        // 一小时的毫秒数
        long nh = 1000 * 60 * 60;
        // 一分钟的毫秒数
        long nm = 1000 * 60;
        // 一秒钟的毫秒数
        long ns = 1000;
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        @SuppressWarnings("unused")
        long sec = 0;
        // 获得两个时间的毫秒时间差异
        try {
            diff = sd.parse(endTime).getTime() - sd.parse(startTime).getTime();
            // 计算差多少天
            day = diff / nd;
            // 计算差多少小时
            hour = diff % nd / nh + day * 24;
            // 计算差多少分钟
            min = (hour * 60) + (diff % nd % nh / nm + day * 24 * 60);
            // 计算差多少秒
            sec = diff % nd % nh % nm / ns;
            // 输出结果
            int minMax = 60;
            if (min > minMax) {
                if (hour > minMax) {
                    result = day + "天";
                } else {
                    result = hour + "小时";
                }
            } else {
                result = min + "分";
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获得当前日期与本周一相差的天数
     */
    private static int getMondayPlus() {
        Calendar cd = Calendar.getInstance();
        // 获得今天是一周的第几天，星期日是第一天，星期二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            return -6;
        } else {
            return 2 - dayOfWeek;
        }
    }

    /**
     * 获得上周星期一的日期
     */
    public static String getPreviousMonday() {
        weeks--;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    /**
     * 获得本周星期一的日期
     */
    public static String getCurrentMonday() {
        weeks = 0;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    /**
     * 获得下周星期一的日期
     */
    public static String getNextMonday() {
        weeks++;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    /**
     * 获得相应周的周日的日期
     */
    public static String getSunday() {
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6);
        Date monday = currentDate.getTime();
        DateFormat df = DateFormat.getDateInstance();
        String preMonday = df.format(monday);
        return preMonday;
    }

    public static String repairDateFormate(String dateStr) {
        String result = dateStr;
        int dataStrLength = 18;
        if (dateStr.length() == dataStrLength) {
            result = dateStr.substring(0, 10) + " " + dateStr.substring(10, dateStr.length());
        }
        return result;
    }


    /**
     * 获取当年的第一天
     *
     * @return
     */
    public static Date getCurrYearFirst(Date date) {
        Calendar currCal = Calendar.getInstance();
        currCal.setTime(date);
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取当年
     */
    public static int getCurrentYear() {
        Calendar c = Calendar.getInstance();
        int currentYear = c.get(Calendar.YEAR);
        return currentYear;
    }

    /**
     * 获取当月
     */
    public static int getCurrentMonth() {
        Calendar c = Calendar.getInstance();
        int currentMonth = c.get(Calendar.MONTH) + 1;
        return currentMonth;
    }

    /**
     * 获取当年的最后一天
     *
     * @return
     */
    public static Date getCurrYearLast(Date date) {
        Calendar currCal = Calendar.getInstance();
        currCal.setTime(date);
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearLast(currentYear);
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取某年最后一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }

    /**
     * 返回星期一字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String getMondayStr(Date date, String format) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
        date = c.getTime();
        String mondayDate = DateUtils.format(date, format);
        return mondayDate;
    }

    /**
     * 返回星期日字符串
     *
     * @param date
     * @param format
     * @return
     */
    public static String getSundayStr(Date date, String format) {
        Calendar c = Calendar.getInstance();
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
        c.add(Calendar.DAY_OF_WEEK, 6);
        //noinspection AlibabaAvoidStartWithDollarAndUnderLineNaming
        Date newDate = c.getTime();
        String sundayDate = DateUtils.format(newDate, format);
        return sundayDate;
    }

    /**
     * time转Date
     *
     * @param time
     * @return
     */
    public static Date parseDate(long time) {
        Date date = null;
        try {
            date = new Date(time);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 根据出生日期计算年龄
     *
     * @param birthDay
     * @return
     */
    public static int getAgeByBirth(Date birthDay) {
        int age = 0;
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) { //出生日期晚于当前时间，无法计算
            return 0;
        }
        int yearNow = cal.get(Calendar.YEAR);  //当前年份
        int monthNow = cal.get(Calendar.MONTH);  //当前月份
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH); //当前日期
        cal.setTime(birthDay);
        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        age = yearNow - yearBirth;   //计算整岁数
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if(dayOfMonthNow < dayOfMonthBirth) {
                    age--;//当前日期在生日之前，年龄减一
                }
            } else {
                age--;//当前月份在生日之前，年龄减一
            }
        }
        return age;
    }

}
